package entity

import (
	"gitee.com/night-tc/gobige/entity/props"
	"gitee.com/night-tc/gobige/global"
	"gitee.com/night-tc/gobige/msgdef/protomsg"
)

/*
Entity对象通讯有关的接口
*/
type IPost interface {
	props.IProps
	IClientSess

	// 同步脏属性给别的服务器和客户端
	SyncDirtyProps()
	// 同步本服务器管理属性给对象目标服务器
	SyncSrvPropsAll(stype global.ServerTypeEnum)
}

/*
对Sess的操作
*/

//-----------------------------------------------------------------------------------

// 同步脏属性给别的服务器和客户端
func (this *Entity) SyncDirtyProps() {
	if this.flyEntity {
		return
	}
	if this.PropsSyncContainer == nil {
		return
	}
	//发消息给别的服务器
	for stype, mli := range this.DirtySrvProps {
		if len(mli) == 0 {
			continue
		}
		this.DirtySrvProps[stype] = mli[:0]
		if smd := this.getSrvByStype(stype); smd == nil {
			continue
		} else {
			msg := new(protomsg.SyncEntityProps)
			msg.Props = props.PackPropsToProtobuf(mli)
			msg.EntityID = this.entityID
			msg.EntityType = this.entityType
			_ = global.GetSrvInst().PostMsgToEntity(smd.SrvID, smd.SpaceID, this.entityID, msg)
		}
	}
	//发消息给自己的客户端
	if len(this.DirtyMRoleMsg) > 0 {
		msg := new(protomsg.SyncEntityProps)
		msg.Props = this.DirtyMRoleMsg
		msg.EntityID = this.entityID
		msg.EntityType = this.entityType
		this.DirtyMRoleMsg = this.DirtyMRoleMsg[:0]
		_ = this.Post(global.ServerTypeClient, msg)
	}
}

// 同步本服务器管理属性给对象目标服务器
func (this *Entity) SyncSrvPropsAll(stype global.ServerTypeEnum) {
	if this.flyEntity {
		return
	}
	if this.PropsSyncContainer == nil {
		return
	}
	m := make([]props.IProp, 0, 10)
	/*
		只会把目标服务器需要，本服务器有的数据；
		同时不是在目标服务器上进行持久化的数；
	*/
	this.ForEachProp(func(p props.IProp) {
		def := p.GetField()
		for _, s := range def.WatchSrvs {
			if s == stype && this.IsExistSID(uint64(s)) &&
				def.MainSrv != stype {
				m = append(m, p)
			}
		}
	})
	if len(m) > 0 {
		msg := new(protomsg.SyncEntityProps)
		msg.Props = props.PackPropsToProtobuf(m)
		msg.EntityID = this.entityID
		msg.EntityType = this.entityType
		_ = this.Post(stype, msg)
	}
}
